package com.shenzhen.horselive.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.renderscript.ScriptGroup;
import android.text.TextUtils;
import android.view.View;

import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.AppBarActivity;
import com.shenzhen.horselive.beans.CashOutRulerBean;
import com.shenzhen.horselive.beans.CommResponseBean;
import com.shenzhen.horselive.beans.CommResponseDataBean;
import com.shenzhen.horselive.beans.UserAcountBean;
import com.shenzhen.horselive.databinding.ActivityCashOutBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.presenter.ViewObserver;
import com.shenzhen.horselive.ui.dialog.CashOutDialog;
import com.shenzhen.horselive.ui.dialog.CommentDialog;
import com.shenzhen.horselive.ui.dialog.InputDialog;
import com.shenzhen.horselive.utils.DialogManager;
import com.shenzhen.horselive.widget.VerificationCodeInput;

import java.text.NumberFormat;

public class CashOutActivity extends AppBarActivity {

    ActivityCashOutBinding  binding;
    CashOutDialog  cashOutDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCashOutBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setStyleDark();
        setTitle("钱包提现");
        initViews();
//        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        //是否有英航卡了
        String  cardno =   User.get().getMyInfo().getCardNo();
        boolean hasbank =  false;
        if (TextUtils.isEmpty(cardno))
        {
            hasbank = false;
        }else
        {
            hasbank = true;
        }

        if (hasbank)
        {
            binding.tvNoBank.setVisibility(View.GONE);
            binding.imgRightArrow.setVisibility(View.GONE);
        }else
        {
            binding.tvNoBank.setVisibility(View.VISIBLE);
            binding.imgRightArrow.setVisibility(View.VISIBLE);
            binding.container.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    //是否实名
                    ApiFactory.getApiService().realNameStatus(User.get().getMyInfo().getToken())
                            .compose(SchedulersCompat.applyIoSchedulers())
                            .safeSubscribe(new LoadingViewObserver<CommResponseDataBean>(CashOutActivity.this) {
                                @Override
                                protected void onNextInActive(CommResponseDataBean commResponseDataBean) {
                                    if (commResponseDataBean.isSuccess())
                                    {
                                        if ("1".equals(commResponseDataBean.getData()))
                                        {
                                            startActivityForResult(new Intent(getContext(),MyBankActivity.class),1000);

                                        }else
                                        {
                                            DialogManager.getInstance().showCommentDialog(getContext(), "你还未实名认证，是否去实名？"
                                                    , "", new CommentDialog.OnClickButton() {
                                                        @Override
                                                        public void confirm() {
                                                            //跳转实名认证
                                                            startActivity(new Intent(getContext(),RealNameAuthActivity.class));
                                                        }

                                                        @Override
                                                        public void cancel() {

                                                        }
                                                    }
                                            );
                                        }
                                    }
                                    else
                                    {
                                        showToast(commResponseDataBean.getErrMessage());
                                    }

                                }
                            });





                }
            });
        }


        //获取钱包的信息
      getAcountForType(0);

      //获取提现的规则
      getRulers();




    }

    private void getRulers() {
        ApiFactory.getApiService().cashOutRulers(User.get().getMyInfo().getToken())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<CashOutRulerBean>(this) {
                    @Override
                    protected void onNextInActive(CashOutRulerBean cashOutRulerBean) {
                        if (cashOutRulerBean.isSuccess())
                        {
                          String rule =
                                  String.format("提示：最低%s元起提，每日提现次数上限%s次，每日可提现金额上限%s元"
                                  ,formatNumber(cashOutRulerBean.getData().getMinWithdrawAmount())
                                          ,formatNumber(cashOutRulerBean.getData().getDayMaxWithdrawCount())
                                          ,formatNumber(cashOutRulerBean.getData().getDayMaxWithdrawAmount())
                                  );
                          binding.tvNoticeRuler.setText(rule);
                        }
                        else
                        {
                            showToast(cashOutRulerBean.getErrMessage());
                        }
                    }
                });
    }

    UserAcountBean  bean;
    //帐户类型: 0:人民币帐户 ,1:蜂值帐户 ,2:红包股帐户 ,3:金卡帐户
    private void getAcountForType(int i) {
        ApiFactory.getApiService().accountTypes(User.get().getMyInfo().getToken(),i+"")
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<UserAcountBean>(this) {
                    @Override
                    protected void onNextInActive(UserAcountBean userAcountBean) {
                        if (userAcountBean.isSuccess())
                        {
                            bean = userAcountBean;
                            NumberFormat  format = NumberFormat.getInstance();
                            format.setMaximumFractionDigits(2);
                            binding.tvNotice.setText(String.format("可提现余额：¥%s",format.format(Double.parseDouble(userAcountBean.getData().getValue()))));
                        }
                        else
                        {
                            showToast(userAcountBean.getErrMessage());
                        }
                    }
                });
    }



    private void initViews() {

       binding.tvCashAll.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               if (bean==null)
                   return;
               NumberFormat  format =  NumberFormat.getInstance();
               format.setMaximumFractionDigits(2);
               String  value = format.format(Double.parseDouble(bean.getData().getValue()));
               binding.etInput.setText(value);
               binding.etInput.setSelection(value.length());
           }
       });

       binding.btGo.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               submit();
           }
       });
        
        
    }

    private void submit() {
        String  num = binding.etInput.getText().toString();
        if (TextUtils.isEmpty(num))
        {
            showToast("请输入提现金额");
            return;
        }
        showPassWordDialog(num);
    }

    private void showPassWordDialog(String num) {
        InputDialog  inputDialog = new InputDialog(this);
        inputDialog.setTextName("确认提现");
        inputDialog.setTextContent(String.format("提现金额：¥%s",num));
            inputDialog.setInputDown(new VerificationCodeInput.Listener() {
                @Override
                public void onComplete(String content) {
                     ApiFactory.getApiService().cashOut(User.get().getMyInfo().getToken()
                     ,num,"3",content)
                             .compose(SchedulersCompat.applyIoSchedulers())
                             .safeSubscribe(new LoadingViewObserver<CommResponseBean>(CashOutActivity.this) {
                                 @Override
                                 protected void onNextInActive(CommResponseBean commResponseBean) {
                                     if (commResponseBean.isSuccess())
                                     {
                                         showToast("提现成功");
                                         finish();
                                     }
                                     else {
                                         showToast(commResponseBean.getErrMessage());
                                     }
                                 }
                             });
                     inputDialog.dismiss();
                }
            });
        inputDialog.show();
    }

    int  paytype =  0;
    private void showChooseDialog() {
        if (cashOutDialog==null)
        {
          String  cardno =   User.get().getMyInfo().getCardNo();
          boolean hasbank =  false;
          if (TextUtils.isEmpty(cardno))
          {
              hasbank = false;
          }else
          {
           hasbank = true;
          }
            cashOutDialog =  new CashOutDialog(this,hasbank);
            cashOutDialog.setOnChooseType(new CashOutDialog.OnChooseType() {
                @Override
                public void ontype(int type) {
                    switch (type)
                    {
                        case 0:
                            binding.imgIco.setImageResource(R.mipmap.ico_weixinpay);
                            binding.tvPayName.setText("微信");
                            paytype = type;
                            break;
                        case 1:
                            binding.imgIco.setImageResource(R.mipmap.ico_alipay);
                            binding.tvPayName.setText("支付宝");
                            paytype = type;
                            break;
                        case 2:
                            ApiFactory.getApiService().realNameStatus(User.get().getMyInfo().getToken())
                                    .compose(SchedulersCompat.applyIoSchedulers())
                                    .safeSubscribe(new LoadingViewObserver<CommResponseDataBean>(CashOutActivity.this) {
                                        @Override
                                        protected void onNextInActive(CommResponseDataBean commResponseDataBean) {
                                            if (commResponseDataBean.isSuccess())
                                            {
                                                if ("1".equals(commResponseDataBean.getData()))
                                                {
                                                 if (cashOutDialog.isHasBank())
                                                 {
//                                                     startActivityForResult(new Intent(getContext(),MyBankActivity.class),1000);
                                                     binding.imgIco.setImageResource(R.mipmap.ico_ying_lian);
                                                     binding.tvPayName.setText("银行卡");
                                                     paytype = type;
                                                 }
                                                 else
                                                 {
                                                     startActivityForResult(new Intent(getContext(),MyBankActivity.class),1000);
                                                 }
                                                }else
                                                {
                                                    DialogManager.getInstance().showCommentDialog(getContext(), "你还未实名认证，是否去实名？"
                                                            , "", new CommentDialog.OnClickButton() {
                                                                @Override
                                                                public void confirm() {
                                                                    //跳转实名认证
                                                                    startActivity(new Intent(getContext(),RealNameAuthActivity.class));
                                                                }

                                                                @Override
                                                                public void cancel() {

                                                                }
                                                            }
                                                    );
                                                }
                                            }
                                            else
                                            {
                                                  showToast(commResponseDataBean.getErrMessage());
                                            }

                                        }
                                    });

                            break;
                    }
                }
            });
        }
        cashOutDialog.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }



    private   String  formatNumber(String  num)
    {
        NumberFormat  format = NumberFormat.getInstance();
        format.setMaximumFractionDigits(10);
        return format.format(Double.parseDouble(num));

    }


}